<?php
/**
 * 打包程序
 * @author Giles <giles.wang@icloud.com>
 *
 * **/
class codesign
{
    //证书
    public $mobileprovision = ''; //mobileprovision 文件
    public $certificate_str  = 'Jiangsu Hualong Continuous Cast Iron Co., Ltd.'; //证书字符串
    public $entitlements     = '';
    public $workDir          = "runTemp";
    public $trueDir          = '';
    public $pack             = "";
    public $fileName         = '';

    public function __construct($pack, $true)
    {
        $this->pack    = $pack;
        $this->trueDir = $true;
        $this->workDir = TRUE_PAK .'runTemp';
    }

    public function run()
    {

        if(empty($this->pack) || empty($this->trueDir)) {
            echo "路径错误";
            return array('error' => '1001', 'message' =>"包名不存在");
        }

        $fileInfo = pathinfo($this->pack);

        saveLog('强签开始:'. $fileInfo['filename']);

        echo $fileInfo['filename'] .".ipa --->任务开始". date('Y-m-d H:i:s'). "\n";

        if(is_dir($this->workDir)) {
            exec("rm -rf ".$this->workDir.'/');
        }

        exec("mkdir ". $this->workDir);
        exec("unzip -d ". $this->workDir ." ". $this->pack,  $ou, $status);
        if($status != 0 ) {
            exec("rm -rf ".$this->workDir.'/');
            return array('error' => '1002', 'message' =>"解压失败");
        }
        exec('cd  '. $this->workDir .' ;find Payload -type d -name "*.app" -o -name "*.appex" -o -name "*.framework"', $dirs);

        $list = $tmp = array();

        $fileInfo = pathinfo($this->pack);

        echo $fileInfo['filename'] .".ipa --->任务创建中". date('Y-m-d H:i:s'). "\n";

        foreach($dirs as $dir) {
            $deep = count(explode("/", $dir));
            $tmp[$deep][] = $dir;
        }
        krsort($tmp);


        foreach($tmp as $deep => $deepdirs) {
            foreach($deepdirs as $deepdir) {
                $list[] = $deepdir;
            }
        }

        exec('cd  '. $this->workDir .' ;find Payload -name "*.dylib"', $dylibs);
        echo $fileInfo['filename'] .".ipa --->进入动态库". date('Y-m-d H:i:s'). "\n";
        if(count($dylibs) > 0) {
            foreach($dylibs as $dylibs) {
                $signdirshell = str_replace(' ', '\ ', addslashes($this->workDir ."/". $dylibs));
                exec("/usr/bin/codesign --force --sign '" . $this->certificate_str .
                    "' --entitlements " . $this->entitlements . " " . $signdirshell, $output);
                if (count($output) > 1) {
                    exec("rm -rf ".$this->workDir.'/');
                    return array('error' => '1005', 'message' =>"强签名失败");
                }
                if (strstr($output [0], 'no identity found')) {
                    exec("rm -rf ".$this->workDir.'/');
                    return array('error' => '1006', 'message' =>"no identity found");
                }
            }
        }



        foreach($list as $signdir) {
            $signdirshell = str_replace(' ', '\ ', addslashes($this->workDir ."/". $signdir));
            exec("rm -rf " . $signdirshell . "/_CodeSignature;rm -rf " . $signdirshell . "/SC_Info;rm -rf " . $signdirshell .
                "/*.mobileprovision;rm -rf " . $signdirshell . "/KY_Channel.plist");

            exec("cp " .$this->mobileprovision . " " . $signdirshell . "/");
            exec("mv " . $signdirshell . "/" . basename($this->mobileprovision) . " " . $signdirshell . "/embedded.mobileprovision");

            exec("/usr/bin/codesign --force --sign '" . $this->certificate_str .
                "' --entitlements " . $this->entitlements . " --deep " . $signdirshell ." 2>&1 ", $output, $status);

            echo $fileInfo['filename'] .".ipa --->修改entitlements". date('Y-m-d H:i:s'). "\n";

            if($status != 0){

                return array('error' => '1002', 'message' => '重签失败');
            };

            if (strstr($output [0], 'no identity found')) {
                exec("rm -rf ".$this->workDir.'/');
                return array('error' => '1008', 'message' => 'no identity found');
            }
        }

        exec("cd ". $this->workDir ." && zip -r temp.ipa ./*");
        exec("mv ". $this->workDir ."/temp.ipa ".$this->trueDir.'/'.$fileInfo['filename'].'.true.ipa');
        exec("rm -rf ".$this->workDir.'/');
        return array('error' => '0000', 'message' => $fileInfo['filename'].'.true.ipa');
    }

}
       function strresin($packInfo, $perfileInfo){

       saveLog('进入任务:');
       exec('security unlock-keychain "-p" "jufeng123" /Users/pack/Library/Keychains/login.keychain');

       $file  = TRUE_PAK.$packInfo['packName'];
       $truePath =  $trueDir = TRUE_PAK.date('Ymd');

       if(!is_dir($trueDir)) {

           exec('mkdir '.$trueDir);
           exec("chmod -R 777".$trueDir);
       }
       signCode($file,$truePath,$perfileInfo);

       }
    /**
     * 签名
     * @param $file 签名文件
     * @param $truePath 签名成功后的路径
     *
     */
    function signCode($file, $truePath,$certificate)
    {
        $file = str_replace('(', '\(', $file);
        $file = str_replace(')', '\)', $file);
        $file = str_replace(' ', '\ ', $file);
        $file = str_replace(';', '\;', $file);
        $file = str_replace('&', '\&', $file);
        $file = str_replace("'", <<<TAG
\'
TAG
            , $file);
        $codesign = new codesign($file, $truePath);


        $termId = $certificate['itermid'];
        $pername  = $certificate['name'];
        $certificate = $certificate['perfileCertificate'];



        $codesign->mobileprovision = PERFILE .$pername;
        $codesign->entitlements    =  PERFILE .".entitlements";
        $codesign->certificate_str = $certificate;



        if(!$codesign->run()) {
            saveLog('强签失败:');
        } else {
            saveLog('强签成功:');
            //exec('rm -rf  '.$file);
        }
        unset($codesign);
        return;
    }

